package com.leadingsoft.pwxk.common;

import java.util.ArrayList;
import java.util.List;

import com.leadingsoft.pwxk.dto.PagingTableDto;
import com.leadingsoft.pwxk.dto.SearchDto;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.jpa.impl.JPAQuery;

/**
 * 
 * @author ysh
 * @desc 分页插件
 */
public class PagingPlugin {

	@SuppressWarnings("rawtypes")
	public static PagingPluginAssist getPagingInfo(JPAQuery<Tuple> query, SearchDto searchDto, OrderSpecifier[] order) {
		long start = 0;
		long size = 10;
		if (searchDto != null) {
			start = (searchDto.getPage() == null ? 0 : searchDto.getPage())
					* (searchDto.getSize() == null ? 10 : searchDto.getSize());
			size = searchDto.getSize() == null ? 10 : searchDto.getSize();
		}
		PagingPluginAssist pagingPluginAssist = new PagingPluginAssist();
		long total = query.distinct().fetchCount();
		query.orderBy(order);
		query.limit(size);
		query.offset(start);
		List<Tuple> fetch = query.distinct().fetch();
		pagingPluginAssist.setList(fetch);
		pagingPluginAssist.setRecordsTotal(total);
		return pagingPluginAssist;
	}

	public static <T> PagingTableDto<T> getLocalPagingInfo(List<T> all, SearchDto searchDto) {
		// 获取所有数据后，手动分页
		int start = 0;
		int size = 10;
		int end = 0;
		if (searchDto != null) {
			start = (searchDto.getPage() == null ? 0 : searchDto.getPage())
					* (searchDto.getSize() == null ? 10 : searchDto.getSize());
			size = searchDto.getSize() == null ? 10 : searchDto.getSize();
		}
		PagingTableDto<T> pagingTableDto = new PagingTableDto<T>();
		List<T> datalist = new ArrayList<T>();
		if (start + size > all.size()) {
			end = all.size();
		} else {
			end = start + size;
		}
		for (int i = start; i < end; i++) {
			datalist.add(all.get(i));
		}
		pagingTableDto.setRecordsTotal(Long.valueOf(all.size()));
		pagingTableDto.setData(datalist);
		return pagingTableDto;
	}
}
